package com.x52im.rainbowchat.manage;

import com.eva.epc.common.util.CommonUtils;
import com.x52im.rainbowchat.cache.ConfigCacheProvider;
import com.x52im.rainbowchat.cache.UsersInfoCacheProvider;
import com.x52im.rainbowchat.cache.dto.UserInfo4Cache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ManagerIndex extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doAll(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doAll(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String type = req.getParameter("type");
        resp.setCharacterEncoding("GBK");
        if (CommonUtils.isStringEmpty(type)) {
            resp.getWriter().print("后缀必须包括type=refreshConfigs, type=refreshUser");
            return;
        }
        if (type.equalsIgnoreCase("refreshConfigs")) {
            refreshConfigs();
            resp.getWriter().print("SUCCESS");
        }
        if (type.equalsIgnoreCase("refreshConfig")) {
            refreshConfig(req.getParameter("id"));
            resp.getWriter().print("SUCCESS");
        }
    }

    private void refreshConfigs() {
        ConfigCacheProvider.getInstance().reloadAllFromDB();
    }

    private void refreshConfig(String id) {
        ConfigCacheProvider.getInstance().reloadOneFromDB(id);
    }

    private void refreshUser(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String uid = req.getParameter("uid");
        if (uid != null && !uid.equals("")) {
            UserInfo4Cache userInfo4Cache = UsersInfoCacheProvider.getInstance().get(uid);
            if (userInfo4Cache != null) {
                resp.getWriter().println(userInfo4Cache.toString());
                return;
            }
        }
    }
}
